package com.company.huisuo.network.auth

import android.content.Context
import android.content.SharedPreferences
import com.company.huisuo.app.MyApp

/**
 * Token管理器
 */
object TokenManager {
    
    private const val PREFS_NAME = "token_prefs"
    private const val KEY_USER_ID = "user_id"
    private const val KEY_ACCESS_TOKEN = "access_token"
    private const val KEY_REFRESH_TOKEN = "refresh_token"
    private const val KEY_EXPIRES_TIME = "expires_time"
    
    private val prefs: SharedPreferences by lazy {
        MyApp.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    }
    
    /**
     * 保存token信息
     */
    fun saveToken(userId: String, accessToken: String, refreshToken: String, expiresTime: Long) {
        prefs.edit().apply {
            putString(KEY_USER_ID, userId)
            putString(KEY_ACCESS_TOKEN, accessToken)
            putString(KEY_REFRESH_TOKEN, refreshToken)
            putLong(KEY_EXPIRES_TIME, expiresTime)
            apply()
        }
    }
    
    /**
     * 获取access token
     */
    fun getAccessToken(): String? {
        return prefs.getString(KEY_ACCESS_TOKEN, null)
    }
    
    /**
     * 获取refresh token
     */
    fun getRefreshToken(): String? {
        return prefs.getString(KEY_REFRESH_TOKEN, null)
    }
    
    /**
     * 获取用户ID
     */
    fun getUserId(): String? {
        return prefs.getString(KEY_USER_ID, null)
    }
    
    /**
     * 获取token过期时间
     */
    fun getExpiresTime(): Long {
        return prefs.getLong(KEY_EXPIRES_TIME, 0)
    }
    
    /**
     * 检查token是否有效
     */
    fun isTokenValid(): Boolean {
        val token = getAccessToken()
        val expiresTime = getExpiresTime()
        return !token.isNullOrEmpty() && System.currentTimeMillis() < expiresTime
    }
    
    /**
     * 检查token是否即将过期（在5分钟内过期）
     */
    fun isTokenAboutToExpire(): Boolean {
        val expiresTime = getExpiresTime()
        return System.currentTimeMillis() > (expiresTime - 5 * 60 * 1000) // 5分钟前
    }
    
    /**
     * 清除所有token信息
     */
    fun clearTokens() {
        prefs.edit().apply {
            remove(KEY_USER_ID)
            remove(KEY_ACCESS_TOKEN)
            remove(KEY_REFRESH_TOKEN)
            remove(KEY_EXPIRES_TIME)
            apply()
        }
    }
    
    /**
     * 更新access token
     */
    fun updateAccessToken(accessToken: String, expiresTime: Long) {
        prefs.edit().apply {
            putString(KEY_ACCESS_TOKEN, accessToken)
            putLong(KEY_EXPIRES_TIME, expiresTime)
            apply()
        }
    }
}